//index.js
//获取应用实例
var app = getApp();
var util = require("../../utils/util.js");
var api = require("../../constant/api.js");
Page({
  data: {
    goodsList: [],
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    isCart: true,
    hasCoupons: false,
    coupons: [],
    couponList:[],
    youhuijine: 0, //优惠券金额
    couponIndex: 0, // 当前选择使用的优惠券
    shippingIndex:0,
    shippingValue: ['express', 'surface', 'ems', 'store', 'cod'],
    shippingType: ['快递', '平邮', 'EMS', '门店配送','上门取货']
  },
  onShow: function () {
    var that = this;
    var shopList = [];
    var currentAddress = wx.getStorageSync("currentAddress");
    //购物车下单
    var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
    that.data.kjId = shopCarInfoMem.kjId;
    if (shopCarInfoMem && shopCarInfoMem.shopList) {
      // shopList = shopCarInfoMem.shopList
      shopList = shopCarInfoMem.shopList.filter(entity => {
        return entity.active;
      });
    }
    that.setData({
      goodsList: shopList
    });
    if (!currentAddress){
      that.createCart();
    }
    that.initShippingAddress();
    
  },

  onLoad: function (e) {
    var that = this;
    //显示收货地址标识
    that.setData({
      orderType: e.orderType
    });
  },

  getDistrictId: function (obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },

  createOrder: function (e) {
    var that = this;
    wx.showLoading();
    var remark = ""; // 备注信息
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }
    
    var postData = {
      message: remark
    };
    if (that.data.kjId) {
      postData.kjid = that.data.kjId;
    }
    if (!that.data.curAddressData) {
      wx.hideLoading();
      wx.showModal({
        title: '错误',
        content: '请先设置您的收货地址！',
        showCancel: false
      })
      return;
    }
    postData.address_id = that.data.curAddressData.address_id;
    
    postData.coupon_id = that.data.coupons.length>0?that.data.coupons[that.data.couponIndex].id:0;
    postData.shipping_type = that.data.shippingValue[that.data.shippingIndex];
    postData.post_fee = that.data.yunPrice;
    postData.payamount = that.data.allGoodsPrice;

    util.request({
      url: '/order/create',
      data: postData, // 设置请求的 参数
      success: (res) => {
        wx.hideLoading();
        if (res.data.code != 0) {
          wx.showModal({
            title: '错误',
            content: res.data.msg,
            showCancel: false
          })
          return;
        }
        
        wx.removeStorageSync('shopCarInfo');
        /*
        // 配置模板消息推送
        var postJsonString = {};
        //订单关闭
        postJsonString.keyword1 = { value: res.data.data.orderNumber, color: '#173177' }
        postJsonString.keyword2 = { value: res.data.data.dateAdd, color: '#173177' }
        postJsonString.keyword3 = { value: res.data.data.amountReal + '元', color: '#173177' }
        postJsonString.keyword4 = { value: '已关闭', color: '#173177' }
        postJsonString.keyword5 = { value: '您可以重新下单，请在30分钟内完成支付', color: '#173177' }
        app.sendTempleMsg(res.data.data.id, -1,
          'gVeVx5mthDBpIuTsSKaaotlFtl5sC4I7TZmx2PtEYn8', e.detail.formId,
          'pages/classification/index', JSON.stringify(postJsonString), 'keyword4.DATA');
        //订单已发货待确认通知
        postJsonString = {};
        postJsonString.keyword1 = { value: res.data.data.orderNumber, color: '#173177' }
        postJsonString.keyword2 = { value: res.data.data.dateAdd, color: '#173177' }
        postJsonString.keyword3 = { value: '已发货' }
        postJsonString.keyword4 = { value: '您的订单已发货，请保持手机通常，如有任何问题请联系客服13722396885', color: '#173177' }
        app.sendTempleMsg(res.data.data.id, 2,
          'ul45AoQgIIZwGviaWzIngBqohqK2qrCqS3JPcHKzljU', e.detail.formId,
          'pages/ucenter/order-details/index?id=' + res.data.data.id, JSON.stringify(postJsonString), 'keyword3.DATA');
        */
        // 下单成功，跳转到订单管理界面
        wx.redirectTo({
          url: "/pages/ucenter/order-list/index"
        });
      }
    })

  },
  createCart: function() {
    var that = this;
    util.request({
      url: '/cart/add',
      data: { carList: this.data.goodsList, activityId: this.data.kjId},
      success: function(res){
        if (res.code == 0){
          wx.removeStorageSync("currentAddress");
        }
        
      }
    },-1);
  },
  initShippingAddress: function () {
    var that = this;
    util.request({
      url: '/user/shipping-address/default',
      data: {},
      success: (res) => {
        if (res.data.code === 0) {
          that.setData({
            curAddressData: res.data.data
          });
          wx.setStorageSync("currentAddress", res.data.data.address_id);
        } else {
          that.setData({
            curAddressData: null
          });
        }
        that.processYunfei();
        that.getMyCoupons();
      }
    })
  },
  processYunfei: function () {
    var that = this;
    //计算运费
    util.request({
      url:"/order/freight",
      data: {
        address_id:that.data.curAddressData.address_id,
        shipping_type: that.data.shippingValue[that.data.shippingIndex]
      },
      success: function(res){
        if(res.data.code == 0){
          that.setData({
            allGoodsPrice: res.data.data.all_goods_price,
            allGoodsAndYunPrice: parseFloat(res.data.data.all_goods_price) + parseFloat(res.data.data.post_fee),
            yunPrice: res.data.data.post_fee
          });
        }
      }
    },-1);
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },
  selectShippingType: function (e) {
    this.setData({
      shippingIndex: e.detail.value
    })
    this.processYunfei();
  },
  getMyCoupons: function () {
    var that = this;
    util.request({
      url: '/order/discounts',
      data: {
        address_id: that.data.curAddressData.address_id,
        shipping_type: this.data.shippingValue[that.data.shippingIndex]
      },
      success: function (res) {
        if (res.data.code === 0) {
          var coupons = res.data.data.filter(entity => {
            return entity.money <= that.data.allGoodsAndYunPrice;
          });
          
          if (coupons.length > 0) {
            var couponList = [];
            for (let i in coupons) {
              couponList.push(coupons[i]['name']);
            }
            console.log(couponList);
            that.setData({
              hasCoupons: true,
              coupons: coupons,
              couponList: couponList
            });
          }
        }
      }
    },-1)
  },
  bindChangeCoupon: function (e) {
    this.setData({
      youhuijine: this.data.coupons[e.detail.value].money,
      couponIndex: e.detail.value
    });
  },
})
